********************************************************************************
******************************Panel A*******************************************
********************************************************************************
set     more off
set     matsize 800
clear   all
global  dpath = "[Userpath]\data and code"

use "$dpath\data\firmdata.dta",clear
g conc=cod/wastewater
sort countycode year

*1.County-level data

foreach var in output wastewater cod nh3n gas so2 dust {
	bysort countycode year: egen `var's = sum(`var')
	drop `var'
	rename `var's `var'
	gen l`var' = log(`var')
}
duplicates drop countycode year, force

gen llgdpC = log(lgdpC)
drop if llgdpC == .

gen llgdp = log(lgdp)
drop if llgdp == .

*2. Remove outliers
winsor2 lwastewater, replace cuts(0.5 99.5) trim
winsor2 lcod, replace cuts(0.5 99.5) trim
winsor2 lgas, replace cuts(0.5 99.5) trim
winsor2 lso2, replace cuts(0.5 99.5) trim
winsor2 ldust, replace cuts(0.5 99.5) trim

*3. Generate variables
xtset countycode year

gen manualupstream = 1 if manualyear != 33000
replace manualupstream = 0 if manualupstream == .

gen treated = 1 if autoupstream == 1 & year >= autoyear
replace treated = 0 if treated == .

gen treatedM = 1 if manualupstream == 1 & year >= manualyear
replace treatedM = 0 if treatedM == .


cd "$dpath\results"

preserve
drop if lwastewater==.
bysort countycode: g N1=_N
bysort citycode year:g N2=_N
drop if N1==1
drop if N2==1

local varlist "lwastewater treated treatedM  llgdpC"
estpost summarize `varlist'
esttab using TableAI.rtf, cells("count mean(fmt(3)) sd(fmt(3))") noobs compress replace 
restore

preserve
drop if lcod==.
bysort countycode: g N1=_N
bysort citycode year:g N2=_N
drop if N1==1
drop if N2==1

estpost summarize lcod
esttab using TableAI.rtf, cells("count mean(fmt(3)) sd(fmt(3))") noobs compress append 
restore

********************************************************************************
******************************Panel B*******************************************
********************************************************************************

set     more off
set     matsize 800
clear   all
global  dpath = "G:\水污染与健康\data and code"

use "$dpath\data\deathratecontrol.dta",clear
cd "$dpath\results"

winsor2 lifeexpectancy, replace cuts(1 99) trim

local healthvar "totaldigestivedr lifeexpectancy digestivecancerdr nocancerdigestivedr accidentdeathrate lungcancerdr respiratorydr cardiovasculardr other tap2000 auto manual lngdp lnbed"
estpost summarize `healthvar'
esttab using TableAI.rtf, cells("count mean(fmt(3)) sd(fmt(3))") noobs compress append 

estpost summarize tap2000 if tapoveraverage==0
esttab using TableAI.rtf, cells("count mean(fmt(3)) sd(fmt(3))") noobs compress append 
estpost summarize tap2000 if tapoveraverage==1
esttab using TableAI.rtf, cells("count mean(fmt(3)) sd(fmt(3))") noobs compress append 

